package secondPart;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Auther : yxpweb
 * @Date : 2021/8/10 10:34
 * @Description: 不停向单线程线程池添加任务，线程内部存在队列
 */
public class ThreadDemo14 {

    // volatile 并不能保证原子性，这样写是错误的
    private static volatile int i;

    private static Runnable gameTask = () -> {
        try {
//            System.out.println(i + "Thread start begin ");
            Thread.sleep(1);
            i++;
            System.out.println(i + "Thread start end ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

    public static void main(String[] args) {
        ThreadPoolExecutor executorService = (ThreadPoolExecutor)Executors.newFixedThreadPool(10);// 这里存在多线程共享数据，会存在并发问题，只能用单线程
//        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 1000000000; i++) {
//            System.out.println(i + "main");
            Future<?> future = executorService.submit(gameTask);
            int size = executorService.getQueue().size();
            System.out.println(size);
        }
        executorService.shutdown();
    }
}
